package com.cancan.demo;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
public class Pdf2Png {
    /**
     * 使用文件流整个pdf转换成图片
     * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
     * @param filename    PDF文件名不带后缀名
     * @param type        图片类型 png 、jpg
     */
    public static List<String> pdfToImage(String fileAddress, String filename, String type) {
        long startTime = System.currentTimeMillis();
        List<String> list = new ArrayList<>();
        Map<String, String> resultMap = null;
        PDDocument pdDocument = null;
        String fileName = null;
        String imgPath = null;
        try {
            // 将文件地址和文件名拼接成路径 注意：线上环境不能使用\\拼接
            //File FilePath = new File("http://192.168.0.60:7000/print/downloadAll//20250410153247-229516.pdf");
            // 文件流
            //FileInputStream inputStream = new FileInputStream(FilePath);
            InputStream inputStream = getInputStreamFromUrl("http://192.168.0.60:7000/print/downloadAll//20250410153247-229516.pdf");
            int dpi = 296;
            pdDocument = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int pageCount = pdDocument.getNumberOfPages();
            /* dpi越大转换后越清晰，相对转换速度越慢 */
            for (int i = 0; i < pageCount; i++) {
                resultMap = new HashMap<>();
                fileName = filename + "_" + (i + 1) + "." + type;
                imgPath = fileAddress + "\\" + fileName;
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                String base64 = encodeBufferedImageToBase64(image);
                System.out.println("Base64 Encoded String : " + base64);
//                ImageIO.write(image, type, new File(imgPath));
//                resultMap.put("fileName", fileName);
//                resultMap.put("filePath", imgPath); // 图片路径
                list.add(base64);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 这里需要关闭PDDocument，不然如果想要删除pdf文件时会提示文件正在使用，无法删除的情况
                pdDocument.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static String encodeBufferedImageToBase64(BufferedImage image) throws IOException {
        // 使用 ByteArrayOutputStream 将 BufferedImage 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos); // 你可以选择其他格式，如 "jpg"
        baos.flush();

        // 将字节数组转换为 Base64 编码的字符串
        byte[] imageBytes = baos.toByteArray();
        String encodedFile = Base64.getEncoder().encodeToString(imageBytes);

        baos.close();
        return encodedFile;
    }

    public static void main(String[] args) throws FileNotFoundException {
        List<String> strings = pdfToImage("D:\\test", "测试", "png");
        for (String string : strings) {
            System.out.println("Base64 Encoded String : " + string);
        }
    }

    private static InputStream getInputStreamFromUrl(String fileURL) throws Exception {
        URL url = new URL(fileURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        // 设置请求方法和超时时间
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setConnectTimeout(5000); // 连接超时时间，单位为毫秒
        httpURLConnection.setReadTimeout(5000);    // 读取超时时间，单位为毫秒

        // 检查响应码
        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 如果响应码为200，表示请求成功，返回InputStream
            return httpURLConnection.getInputStream();
        } else {
            System.out.println("服务器响应码: " + responseCode);
            return null;
        }
    }


}
